package com.ys.peony.ui.activity;

import android.annotation.SuppressLint;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.LinearLayout;

import com.yklab.library.list.inter.EndRecyclerOnScrollListener;
import com.yklab.library.refreshlayout.BGANormalRefreshViewHolder;
import com.yklab.library.refreshlayout.BGARefreshLayout;
import com.yklab.library.refreshlayout.adapters.NewCommonRecyclerViewAdapter;
import com.yklab.library.ui.adapter.LoadMoreWrapper;
import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.interfaces.IsearchView;
import com.ys.peony.ui.widget.SimpleTitleLayout;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public abstract class ListActivity<T> extends BaseActivity implements BGARefreshLayout.BGARefreshLayoutDelegate, IsearchView<T> {
    Toolbar toolbar;
    LinearLayout view_actionbar;
    LinearLayout view_toolbar;
    LinearLayout rootview;
    SearchView mSearchView;
    SearchView.SearchAutoComplete mSearchAutoComplete;
    BGARefreshLayout refreshlayout;
    RecyclerView recyclerview;
    Boolean isShowToolbar = false;
    LinearLayout view_blank;
    @BindView(R.id.view_stub)
    ViewStub view_stub;
    protected NewCommonRecyclerViewAdapter mAdapter;
    protected List<T> mRequestList; //请求数据
    protected List<T> mList; //显示数据
    protected RecyclerView.LayoutManager mLayoutManager;
    public SimpleTitleLayout titleLayout;
    protected LoadMoreWrapper mLoadMoreWrapper;
    //动作类型
    protected int actionType = YSConstant.INVALID;
    protected int curPageNum = 0;

    @Override
    protected int getContentResId() {
        return R.layout.activity_list;
    }

    @Override
    protected void initView() {
        initWidget();
        initData();
        initMenu();
        initListener();
    }

    private void initWidget() {
        view_actionbar = $(R.id.view_actionbar);
        view_toolbar = $(R.id.view_toolbar);
        titleLayout = $(R.id.titleview);
        refreshlayout = $(R.id.refreshlayout);
        recyclerview = $(R.id.recyclerview);
        toolbar = $(R.id.toolbar);
        view_stub = $(R.id.view_stub);
        rootview = $(R.id.rootview);
    }

    private void initData() {
        if (isShowToolbar) {
            view_toolbar.setVisibility(View.VISIBLE);
            view_actionbar.setVisibility(View.GONE);
        } else {
            view_toolbar.setVisibility(View.GONE);
            view_actionbar.setVisibility(View.VISIBLE);
        }
        mList = new ArrayList<>();
        mRequestList = new ArrayList<>();
    }

    private void initListener() {
        refreshlayout.setDelegate(this);
        refreshlayout.setDelegate(this);
        // 设置下拉刷新和上拉加载更多的风格;参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        refreshlayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(this, true));
        recyclerview.addOnScrollListener(new EndRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                if (mLoadMoreWrapper.getLoadState() == LoadMoreWrapper.LOADING
                        || mLoadMoreWrapper.getLoadState() == LoadMoreWrapper.LOADING_END) {
                    return;
                }
                mLoadMoreWrapper.setLoadState(LoadMoreWrapper.LOADING);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        actionType = YSConstant.ACTION_TYPE_UP;
                        curPageNum++;
                        getData();
                        mLoadMoreWrapper.setLoadState(LoadMoreWrapper.LOADING_COMPLETE);
                    }
                }, 1000);

            }

            @Override
            public void onFirstItem() {

            }

            @Override
            public void onScroll(int position) {

            }
        });
    }

    /**
     * 描述：初始化menu
     */
    private void initMenu() {
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSearchAutoComplete.isShown()) {
                    try {
                        mSearchAutoComplete.setText("");
                        Method method = mSearchView.getClass().getDeclaredMethod("onCloseClicked");
                        method.setAccessible(true);
                        method.invoke(mSearchView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    finish();
                }
            }
        });
        toolbar.setTitle("客户签约列表");
    }

    @SuppressLint("RestrictedApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search_view, menu);
        MenuItem searchItem = menu.findItem(R.id.menu_search);
        //通过MenuItem得到SearchView
        mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        mSearchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(R.id.search_src_text);
        mSearchView.setQueryHint("搜索通过姓名或编号");

        //设置输入框提示文字样式
        /*mSearchAutoComplete.setHintTextColor(getResources().getColor(android.R.color.darker_gray));
        mSearchAutoComplete.setTextColor(getResources().getColor(android.R.color.background_light));*/
        mSearchAutoComplete.setTextSize(14);
        //设置触发查询的最少字符数（默认2个字符才会触发查询）
        mSearchAutoComplete.setThreshold(1);

        //设置搜索框有字时显示叉叉，无字时隐藏叉叉
        mSearchView.onActionViewExpanded();
        mSearchView.setIconified(true);

        //修改搜索框控件间的间隔（这样只是为了更加接近网易云音乐的搜索框）
        LinearLayout search_edit_frame = (LinearLayout) mSearchView.findViewById(R.id.search_edit_frame);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) search_edit_frame.getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
        search_edit_frame.setLayoutParams(params);

        //监听SearchView的内容
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                searchData(s.toString().trim(), getUrl());
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                observerSearchText(mRequestList, s.toString().trim());
                return false;
            }
        });
        mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                mList.clear();
                mList.addAll(mRequestList);
                mLoadMoreWrapper.notifyDataSetChanged();
                return false;
            }
        });
        mSearchView.setOnSearchClickListener(new SearchView.OnClickListener() {

            @Override
            public void onClick(View view) {
                mList.clear();
                mLoadMoreWrapper.notifyDataSetChanged();
            }
        });
        return true;
    }

    public Boolean getShowToolbar() {
        return isShowToolbar;
    }

    public void setShowToolbar(Boolean showToolbar) {
        isShowToolbar = showToolbar;
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        curPageNum = 0;
        actionType = YSConstant.ACTION_TYPE_DOWN;
        getData();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }

    protected abstract void getData();

    protected abstract String getUrl();


    @Override
    public void searchData(String searchKeyStr, String url) {
        if (TextUtils.isDigitsOnly(searchKeyStr)) {
            return;
        }
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));
        params.put("clientName", searchKeyStr);
        params.put("currentPage", 0);
        if (HttpURL.sectionList.equals(url)) {
            params.put("section", YSConstant.DAIMIANSHEN);
        }
        params.put("pageNum", 9999);
        httpManager.get(url, params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                searchData(respStr);
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }

    @Override
    public abstract void observerSearchText(List list, String text);

    protected abstract void searchData(String respStr);

    protected void showBlankView() {
        if (!(view_stub.getVisibility() == View.VISIBLE)) {
            view_stub.inflate();
            view_blank = findViewById(R.id.view_blank);
        }
        view_blank.setVisibility(View.VISIBLE);
        refreshlayout.setVisibility(View.GONE);
    }

    protected void hideBlankView() {
        if (view_blank != null) {
            view_blank.setVisibility(View.GONE);
        }
        refreshlayout.setVisibility(View.VISIBLE);
    }

}
